package com.ruoyi.client.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.client.annotation.Client_oper;
import com.ruoyi.client.annotation.TargetJson;
import com.ruoyi.client.domain.entity.*;
import com.ruoyi.client.domain.page.ClientPageParam;
import com.ruoyi.client.domain.vo.CHArticleVo;
import com.ruoyi.client.domain.vo.EchartsVo;
import com.ruoyi.client.eum.ClientBusinessType;
import com.ruoyi.client.service.*;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.mybatis.core.page.PageQuery;
import com.ruoyi.common.mybatis.core.page.TableDataInfo;
import com.ruoyi.common.web.core.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

@RestController
@RequestMapping("client/user/article")
public class BlogArticleController extends BaseController {
    @Autowired
    IBlogArticleService articleService;
    @Autowired
    IBlogHistoryService historyService;
    @Autowired
    IBlogCategoryService categoryService;
    @Autowired
    IBlogUserService userService;
    @Autowired
    IBlogCollectService collectService;
    @Autowired
    MongoTemplate mongoTemplate;
    //用户端
    @GetMapping("addArticleNum")
    public R<List<EchartsVo>> getAddCommentNum(){
        Long userId = Long.valueOf((String) StpUtil.getLoginId());
        // 获取当前日期
        LocalDate today = LocalDate.now();
        // 获取7天前的日期
        LocalDate sevenDaysAgo = today.minusDays(6); // 包括今天，所以减去6天
        // 获取最近7天的开始时间（7天前的 00:00:00）
        LocalDateTime startOfLastSevenDays = sevenDaysAgo.atStartOfDay();
        // 获取最近7天的结束时间（今天的 23:59:59.999999999）
        LocalDateTime endOfLastSevenDays = today.atTime(LocalTime.MAX);
        List<EchartsVo> result = articleService.addLikeNum(userId,startOfLastSevenDays,endOfLastSevenDays);
        return R.ok(result);
    }
    /**
     * 获取已发布文章列表
     * @param pageParam
     * @return
     */
    @GetMapping("publishList")
    public TableDataInfo<BlogArticle> getPulishList(ClientPageParam<BlogArticle> pageParam){
        Long userId = Long.valueOf((String) StpUtil.getLoginId());
        TableDataInfo<BlogArticle> result = articleService.getPublishPage(userId,pageParam);
        return result;
    }
    /**
     * 获取文章草稿列表
     * @param pageParam
     * @return
     */
    @GetMapping("draftList")
    public TableDataInfo<BlogArticle> getDraftList(ClientPageParam<BlogArticle> pageParam){
        Long userId = Long.valueOf((String) StpUtil.getLoginId());
        TableDataInfo<BlogArticle> result = articleService.getDraftPage(userId,pageParam);
        return result;
    }

    /**
     * 查看博客
     * @param id
     * @param url
     * @return
     */
    @GetMapping("client/{id}")
    @SaIgnore
    public R<BlogArticle> getInfoClient(@PathVariable Long id,@RequestParam("url") String url){
        Long userId = Long.valueOf((String) StpUtil.getLoginId());
        BlogArticle article = articleService.getById(id);
        // 更新文章浏览量
        UpdateWrapper<BlogArticle> wrapper = new UpdateWrapper();
        wrapper.setSql("watch_num = watch_num + 1")
            .eq("id", id);
        articleService.update(wrapper);
        // 更新用户总浏览量
        UpdateWrapper<BlogUser> userWrapper = new UpdateWrapper<>();
        userWrapper.setSql("total_watch_num = total_watch_num + 1")
            .eq("id", userId);
        userService.update(userWrapper);
        // 将浏览记录保存到mongoDb中
        LocalDate localDate = LocalDate.now();
        Criteria condition = Criteria.where("date").is(localDate).where("targetId").is(article.getId());
        Query query = Query.query(condition);
        MWatch mWatch = mongoTemplate.findOne(query, MWatch.class);
        if (mWatch == null){
            mWatch = new MWatch();
            mWatch.setDate(localDate);
            mWatch.setUserId(article.getUserId());
            mWatch.setTargetId(article.getId());
            HashSet<Long> set = new HashSet<>();
            set.add(userId);
            mWatch.setWatchedIds(set);
            mWatch.setCount(1L);
        } else {
            mWatch.setCount(mWatch.getCount() + 1);
            mWatch.getWatchedIds().add(userId);
        }
        mongoTemplate.save(mWatch,"watch");
        // 保存历史记录
        BlogHistory history = new BlogHistory();
        history.setTargetId(article.getId());
        history.setUrl(url);
        List<BlogHistory> list = historyService.list(Wrappers.<BlogHistory>lambdaQuery()
            .eq(BlogHistory::getTargetId, article.getId())
            .eq(BlogHistory::getUserId, userId)
            .orderByDesc(Arrays.asList(BlogHistory::getUpdateTime, BlogHistory::getCreateTime))
        );
        if (CollectionUtil.isNotEmpty(list)) {
            BlogHistory lastly = list.get(list.size() - 1);
            LocalDateTime updateTime = lastly.getUpdateTime();
            LocalDateTime createTime = lastly.getCreateTime();
            // 判断更新时间或创建时间是否在今天
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime startOfDay = now.with(LocalTime.MIN); // 今天的开始时间（00:00:00）
            LocalDateTime endOfDay = now.with(LocalTime.MAX);   // 今天的结束时间（23:59:59.999999999）
            if (updateTime != null) {
                if (updateTime.isAfter(startOfDay) && updateTime.isBefore(endOfDay)){
                    // 更新
                    historyService.update(history,Wrappers.<BlogHistory>lambdaUpdate()
                        .eq(BlogHistory::getTargetId, article.getId())
                        .eq(BlogHistory::getUserId, userId)
                    );
                }else {
                    // 不在当天
                    history.setUserId(userId);
                    historyService.save(history);
                }
            }
            else {
                if (createTime.isAfter(startOfDay) && createTime.isBefore(endOfDay)){
                    // 更新
                    historyService.update(history,Wrappers.<BlogHistory>lambdaUpdate()
                        .eq(BlogHistory::getTargetId, article.getId())
                        .eq(BlogHistory::getUserId, userId)
                    );
                }else {
                    // 不在当天
                    history.setUserId(userId);
                    historyService.save(history);
                }
            }
        }else {
            history.setUserId(userId);
            historyService.save(history);
        }
        return R.ok(article);
    }

    /**
     * 历史记录
     * @param pageParam
     * @return
     */
    @GetMapping("historyArticle")
    public TableDataInfo<CHArticleVo> getHistoryArticle(ClientPageParam<CHArticleVo> pageParam){
        Long userId = Long.valueOf((String) StpUtil.getLoginId());
        TableDataInfo<CHArticleVo> result = articleService.getHistroryPage(userId,pageParam);
        return result;
    }
    /**
     * 收藏博客
     * @param pageParam
     * @return
     */
    @GetMapping("collectArticle")
    public TableDataInfo<CHArticleVo> getCollectArticle(ClientPageParam<CHArticleVo> pageParam){
        Long userId = Long.valueOf((String) StpUtil.getLoginId());
        TableDataInfo<CHArticleVo> result = articleService.getCollectPage(userId,pageParam);
        return result;
    }
    /**
     * 列表
     * @param pageQuery
     * @param article
     * @return
     */
    @GetMapping("list1")
    public TableDataInfo<BlogArticle> list1(PageQuery pageQuery,BlogArticle article){
        TableDataInfo<BlogArticle> result = articleService.getArticleAll(pageQuery,article);
        return result;
    }
    @PostMapping
    @Client_oper(title = "发布文章",clientBusinessType = ClientBusinessType.TYPE_PUBLISH)
    public R add(@RequestBody @TargetJson BlogArticle article){
        Long userId = Long.valueOf((String) StpUtil.getLoginId());
        article.setUserId(userId);
        if (article.getId() != null){
            articleService.updateById(article);
        }
        else {
            boolean save = articleService.save(article);
            // 更新文章分类 使用数量
            UpdateWrapper<BlogCategory> wrapper = new UpdateWrapper<>();
            wrapper.setSql("use_num = use_num + 1").eq("id",article.getCategoryId());
            categoryService.update(wrapper);
        }
        return toAjax(true);
    }

    // 管理端
    @GetMapping("list")
    public TableDataInfo<BlogArticle> list(PageQuery pageQuery){
        return articleService.getArticleByCategoryType(pageQuery);
    }
    @GetMapping("/{id}")
    public R<BlogArticle> getInfo(@PathVariable Long id){
        BlogArticle article = articleService.getById(id);
        return R.ok(article);
    }
    @PutMapping
    public R update(@RequestBody BlogArticle article){
        boolean b = articleService.updateById(article);
        return toAjax(b);
    }
    @DeleteMapping("/{ids}")
    public R delete(@PathVariable Long[] ids){
        boolean b = articleService.removeBatchByIds(Arrays.asList(ids));
//        // 删除收藏表中数据，减少发布用户发布数，减少收藏用户收藏数
//        List<BlogCollect> collectList = collectService.list(Wrappers.<BlogCollect>lambdaQuery().in(BlogCollect::getTargetId, ids));
//        ArrayList<Long> idList = new ArrayList<>();
//        HashMap<Long, Long> countList = new HashMap<>();
//        collectList.forEach(v -> {
//            idList.add(v.getId());
//
//        });
        return toAjax(b);
    }
}
